<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use App\Models\Menu;
use App\Models\Role;
use App\Models\RoleMenu;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JWTAuth;
use Illuminate\Support\Facades\Cookie;
class LoginController extends Controller
{

    /**
     * 登录
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function   index()
    {



        return view('admin/login');
    }



    /**
     * 后台登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        //验证用户输入
        $params = $request->only(['username', 'password']);
        $validator = \Validator::make($params, [
            'username' => 'required|exists:admin',
            'password' => 'required',
        ], [
            'username.*' => '没有对应的信息',
            'password.*' => '密码必填',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $admin = Admin::where('username', $request->username)->first();
        if (\Hash::check($request->password, $admin->password)) {
//            $jwt_token = JWTAuth::fromUser($admin);
            $cookie = cookie('admin_id', $admin->id, 360);

            return  $this->success(array('status' => 1, 'msg' => '登录成功'))->cookie($cookie);
//            return $this->success(['token' => 'bearer ' . $jwt_token, 'user' => $admin,'msg'=>'登录成功']);
        }


        return $this->error('密码错误');

    }

    /**
     * 登录账号的路由
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userMenu(Request $request)
    {
//        $user = \Auth::user();
//        $menu_ids = RoleMenu::where('role_id', $user->role_id)->pluck('menu_id');
//
//        Menu::whereIn('id',$menu_ids)->get();
        $data = $this->getMenu();
        return  $this->success(['data'=>$data]);
    }

    /**
     * 递归获取路由
     * @param int $pid
     * @param int $level
     * @return array
     */
    public function getMenu($pid=0,$level=1)
    {
        $list = Menu::where('p_id', $pid)->where('level',$level)->get();
        if($list->first()){
              $data=[];
            foreach ($list as $key=>$item){
                $data[$key]=$item;
                $children = $this->getMenu($item->id,$item->level+1);
                if($children){
                    $data[$key]['children'] =$children;
                }
            }

            return $data;
        }

    }

    /**
     * 退出
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public  function  out_login()
    {
        Cookie::queue(Cookie::forget('admin_id'));

        return redirect('/admin/login/index');
    }
}
